import os
import math
import time

# 利用os模块编写一个能实现dir - l输出的程序。
#
# 编写一个程序，能在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件，并打印出相对路径。
from os.path import getsize, join


def shiftTime(localTime):
    return time.strftime("%Y/%m/%d %H:%M", time.localtime(localTime))


def getName(item):
    # 返回文件前缀
    return item.split('.')[0]


def getSize(item):
    if item < 1024:
        return f"{item}B"
    elif item < 1024 ** 2:
        return f"{math.ceil(item / 1024)}KB"
    else:
        return f"{math.ceil(item / 1024 ** 2)}MB"


def dir_l(path, span):
    # print(f"您要查看{path}目录下的文件信息")
    # print(path)
    # allInfo = [x for x in os.listdir(path)]
    allfiles = sorted([x for x in os.listdir(path) if os.path.isfile(os.path.join(path, x))], reverse=False)
    alldirs = sorted([x for x in os.listdir(path) if os.path.isdir(os.path.join(path, x))], reverse=False)
    for i in allfiles:
        newPath = os.path.join(path, i)
        space = span * "--"
        print('|' + space, end='')
        print(
            f"名称：{i}  修改日期：{shiftTime(os.path.getmtime(newPath))}   大小：{getSize(os.path.getsize(newPath))}")

    for i in alldirs:
        newPath = os.path.join(path, i)
        space = span * "--"
        print('|' + space, end='')
        print(
            f"名称：{i}  修改日期：{shiftTime(os.path.getmtime(newPath))}   大小：{getSize(getdirsize(newPath))}")
        dir_l(newPath, span + 1)

def getdirsize(dir):
    size = 0
    for root, dirs, files in os.walk(dir):
        # print(files)
        size += sum([getsize(join(root, name)) for name in files])
    return size


if __name__ == '__main__':
    dir_l(os.path.abspath(r'.'), 0)